package com.gitee.ixtf.lucene

import com.gitee.ixtf.lucene.Jlucene.ID
import com.gitee.ixtf.lucene.Jlucene.LUCENE_PATH
import com.gitee.ixtf.lucene.command.LuceneAllCommand
import com.gitee.ixtf.lucene.command.LuceneOneCommand
import java.io.Closeable
import java.lang.reflect.ParameterizedType
import org.apache.lucene.index.*
import org.apache.lucene.search.IndexSearcher
import org.apache.lucene.store.FSDirectory
import org.apache.lucene.util.IOUtils

abstract class BaseLucene<T> : Closeable {
  @Suppress("UNCHECKED_CAST")
  protected val entityClass by lazy {
    val parameterizedType = javaClass.genericSuperclass as ParameterizedType
    parameterizedType.actualTypeArguments[0] as Class<T>
  }
  protected open val analyzer by Jlucene::ANALYZER
  protected open val indexWriter by lazy {
    val indexPath = LUCENE_PATH.resolve(entityClass.simpleName)
    IndexWriter(FSDirectory.open(indexPath), IndexWriterConfig(analyzer))
  }

  override fun close() = IOUtils.close(indexWriter)

  open fun commit(): Long = indexWriter.commit()

  fun indexReader(): IndexReader = DirectoryReader.open(indexWriter)

  fun indexSearcher(): IndexSearcher = IndexSearcher(indexReader())

  abstract suspend fun index(command: LuceneOneCommand): Long

  open suspend fun delete(command: LuceneOneCommand): Long =
      indexWriter.deleteDocuments(Term(ID, command.id))

  abstract suspend fun index(command: LuceneAllCommand)
}
